package com.zhan.ielts.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhan.frame.core.web.domain.CustomResult;
import com.zhan.ielts.domain.Merchandise;
import com.zhan.ielts.service.MerchandiseService;

@Controller
@RequestMapping("/merchandise")
public class MerchandiseController {

	private Logger log = LoggerFactory.getLogger(MerchandiseController.class);

	@Autowired
	private MerchandiseService merchandiseService;

	@ResponseBody
	@RequestMapping(value = "/fetch", method = RequestMethod.POST)
	public CustomResult fetch(String type) {
		log.debug("获取商品信息开始");
		Map<String, Object> map = new HashMap<>();
		List<Merchandise> merchandiseList = null;
		try {
//			int page = 0;
//			int pageSize = 5;
//			Sort sort = new Sort(Direction.ASC, "duration");
//			Pageable pageable = new PageRequest(page, pageSize, sort);
//			Merchandise query = new Merchandise();
//			query.setSubject(type);
//			merchandiseList = merchandiseService.queryList(query, pageable);
			
//			Sort sort = new Sort(Direction.ASC, "duration");
//			Pageable pageable = new PageRequest(0, Integer.MAX_VALUE, sort);
			//merchandiseService.fetchMerchandise(type, pageable);
			map.put("isShowBuy", "N");
			
			
		} catch (Exception e) {
			log.debug("获取商品信息失败！");
			map.put("errCode", 1001);
			return new CustomResult(0, "系统错误, 获取商品信息失败！", map);
		}
		log.debug("获取商品信息结束");

		return new CustomResult(1,"", map);
	}

	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public CustomResult update(Merchandise entity) {
		log.debug("更新商品信息开始");
		Map map = new HashMap();
		if (StringUtils.isEmpty(entity.getSubject())) {
			return new CustomResult(0, "商品的名（subject）为空！", map);
		} else if (StringUtils.isEmpty(entity.getDuration())) {
			return new CustomResult(0, "商品的期间（duration）为空！", map);
		} else if (StringUtils.isEmpty(entity.getPrice())) {
			return new CustomResult(0, "商品的价格（price）为空！", map);
		}

		if (StringUtils.isEmpty(entity.getStatus())) {
			entity.setStatus(1);
		}

		try {
			entity.setUpdateTime(System.currentTimeMillis());
			merchandiseService.insert(entity);
		} catch (Exception e) {
			log.debug("更新商品信息失败！");
			e.printStackTrace();
			return new CustomResult(0, "系统错误, 更新商品信息失败！", map);
		}
		log.debug("更新商品信息结束");

		return new CustomResult(1, "",map);
	}
}
